from collections import deque

# 带有外部状态的生成器函数, 想定义一个生成器函数，但是它会调用某个想暴露给用户使用的外部状态值
# 可以简单的将它实现为一个类，然后把生成器函数放到__iter__()方法中过去
class linehistory:
    def __init__(self, lines, histlen=3):
        self.lines = lines
        self.history = deque(maxlen=histlen)

    def __iter__(self):
        for lineno, line in enumerate(self.lines, 1):
            self.history.append((lineno, line))
            yield line

    def clear(self):
        self.history.clear()

def demo_1():
    with open('../temp/pome.txt') as f:
        lines = linehistory(f)
        for line in lines:
            if 'python' in line:
                for lineno, hline in lines.history:
                    print('{}:{}'.format(lineno, hline), end='')

if __name__ == '__main__':
    demo_1()